const path = require('path');
const resolve = dir => path.join(__dirname, dir);
// 是否为生产环境
const isProduction = process.env.NODE_ENV !== 'development';
// 本地环境是否需要使用cdn
const devNeedCdn = true

// gzip压缩
const CompressionWebpackPlugin = require('compression-webpack-plugin')

// CDN
const cdn = {
  externals: {
    vue: 'Vue',
    vuex: 'Vuex',
    axios: 'axios',
    'element-ui': 'ELEMENT',
    'vue-router': 'VueRouter'
  },
  // js的cdn链接
  js: [
    'https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/vue/2.6.11/vue.min.js',
    'https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/vuex/3.5.1/vuex.min.js',
    'https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/vue-router/3.4.8/vue-router.min.js',
    'https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/axios/0.21.0/axios.min.js',
    'https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/element-ui/2.15.7/index.min.js'
  ],
  // css
  css: [
    'https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/element-ui/2.15.7/theme-chalk/index.min.css'
  ]
}

module.exports = {
  configureWebpack: config => {
    // 用cdn方式引入，则构建时要忽略相关资源
    if (isProduction || devNeedCdn) config.externals = cdn.externals
    if (isProduction) {
      // gzip压缩
      const productionGzipExtensions = ['html', 'js', 'css']
      config.plugins.push(
        new CompressionWebpackPlugin({
          filename: '[path].gz[query]',
          algorithm: 'gzip',
          test: new RegExp(
            '\\.(' + productionGzipExtensions.join('|') + ')$'
          ),
          threshold: 10240, // 只有大小大于该值的资源会被处理 10240
          minRatio: 0.8, // 只有压缩率小于这个值的资源才会被处理
          deleteOriginalAssets: false // 删除原文件
        })
      )
    }
  },
  chainWebpack: config => {
    // ============注入cdn start============
    config.plugin('html').tap(args => {
      // 生产环境或本地需要cdn时，才注入cdn
      if (isProduction || devNeedCdn) args[0].cdn = cdn
      args[0].title = '后台管理中心'
      return args
    })
    // ============注入cdn start============
    // // ============压缩图片 start============
    // config.module
    //   .rule('images')
    //   .use('image-webpack-loader')
    //   .loader('image-webpack-loader')
    //   .options({
    //     bypassOnDebug: true
    //   })
    //   .end()
    // // ============压缩图片 end============
    // 移除 prefetch 插件
    config.plugins.delete('prefetch');
    // 移除 preload 插件
    config.plugins.delete('preload');
    // 压缩代码
    config.optimization.minimize(true);
    // 分割代码
    config.optimization.splitChunks({
      chunks: 'all'
    });

    config.resolve.alias
      .set('vue$', 'vue/dist/vue.esm.js')
      // .set('@', resolve('src'))
      .set('@public', resolve('src/pages/public'));
  },
  css: {
    sourceMap: false,
    loaderOptions: {
      scss: {
        // 向全局sass样式传入共享的全局变量, $src可以配置图片cdn前缀
        // 详情: https://cli.vuejs.org/guide/css.html#passing-options-to-pre-processor-loaders
        prependData: `
          @import "./public/static/css/color.scss";
          @import "./public/static/css/prefix.scss";
          `
      }
    }
  },
  devServer: {
    overlay: { // 让浏览器 overlay 同时显示警告和错误
      warnings: true,
      errors: true
    },
    open: true, // 是否打开浏览器
    host: 'localhost',
    port: '8080', // 代理端
    https: false,
    hotOnly: false, // 热更新
    proxy: {
      '/api': {
        target: 'http://127.0.0.1/', // 接口地址
        secure: false,
        changeOrigin: true, // 开启代理，在本地创建一个虚拟服务端
        pathRewrite: { // 路径重写，
          '^/api/': '/' // 替换target中的请求地址，也就是说以后你在请求http://api.douban.com/v2/XXXXX这个地址的时候直接写成/api即可。
        }
      }
    }
  },
  outputDir: process.env.NODE_ENV === 'development' ? './build/dist/' : './build/' + process.env.NODE_ENV,
  assetsDir: 'static',
  indexPath: 'index.html',
  productionSourceMap: false

}
